package com.itheima.service.impl;

import com.itheima.entity.Category;
import com.itheima.entity.Movies;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.MoviesMapper;
import com.itheima.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private MoviesMapper moviesMapper;

    @Override
    public Map<String, List<Movies>> findMovieListMap() {
        // 查询所有分类数据
        List<Category> categories = categoryMapper.findAll();

        // 查询所有电影数据
        List<Movies> movies = moviesMapper.findAll();

        // 根据分类组装数据
        Map<String, List<Movies>> movieListMap = new HashMap<>();

        // 遍历分类并过滤出该分类下的电影数据
        for (Category category : categories) {
            // 新建一个空列表，用来存储当前分类下的电影
            List<Movies> filteredMovies = new ArrayList<>();

            // 遍历所有电影，检查当前电影的分类ID是否与当前分类ID匹配
            for (Movies movie : movies) {
                if (movie.getCid().equals(category.getId())) {
                    filteredMovies.add(movie); // 如果匹配，加入到当前分类的电影列表中
                }
            }

            // 把当前分类名和对应的电影列表放入最终的 Map 中
            movieListMap.put(category.getCategoryName(), filteredMovies);
        }
        return movieListMap;
    }
}
